package com.ctgu.redislock01.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @ClassName RedisConfigForObject
 * @Author Alex2
 * @Date 2025/2/25 11:54
 **/
@Configuration
public class RedisConfigForObject {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 创建 RedisTemplate 对象
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 使用 Jackson2JsonRedisSerializer 序列化器
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);

        // 设置JavaTimeModule
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        serializer.setObjectMapper(objectMapper);

        // 设置 Key 和 Value 的序列化器
        redisTemplate.setKeySerializer(new StringRedisSerializer());        // 设置键的序列化方式为 String
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());    // 哈希键的序列化
        redisTemplate.setValueSerializer(serializer);                       // 设置值的序列化方式为 Jackson
        redisTemplate.setHashValueSerializer(serializer);                   // 哈希值的序列化

        return redisTemplate;
    }
}
